from PySide6.QtCore import QThread, QIODeviceBase, Slot, Signal, QByteArray
from PySide6.QtSerialPort import QSerialPort


class SerialModel(QThread):
    signal_open_result = Signal(bool)
    signal_send_msg = Signal(QByteArray)

    def __init__(self, caller):
        super().__init__()

        self.m_serial = QSerialPort()
        self.m_serial.readyRead.connect(self.read_msg)

    @Slot(tuple)
    def open_serial(self, para):
        self.m_serial.setPort(para[0])
        self.m_serial.setBaudRate(para[1])
        self.m_serial.setStopBits(para[2])
        self.m_serial.setDataBits(para[3])
        self.m_serial.setParity(para[4])
        self.m_serial.setFlowControl(para[5])

        # 通知界面连接结果
        self.signal_open_result.emit(self.m_serial.open(QIODeviceBase.ReadWrite))

    @Slot()
    def close_serial(self):
        if self.m_serial.isOpen() is True:
            self.m_serial.close()
            self.signal_open_result.emit(False)

    @Slot(QByteArray)
    def send_msg(self, msg):
        if self.m_serial.isOpen() is True:
            self.m_serial.write(msg)

    @Slot()
    def read_msg(self):
        text = self.m_serial.readAll()
        if text.isEmpty() is False:
            self.signal_send_msg.emit(text)
